import React from 'react';
import {browserHistory,Link} from 'react-router';
import { Form, Button, Input, Select, message,Modal } from 'antd';
import ajax from '../../common/ajax';
import config from '../../config/config';
import $ from 'jquery';
const token = sessionStorage.getItem('token');
const allRouter=config.router;
const FormItem = Form.Item;
const Option = Select.Option;
class AddFirstDepartment extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            relatedDoctorList:[],
            handnamed:false,//判断是否重名,修改
        };
        this.saveData = this.saveData.bind(this);
        this.cancelSave = this.cancelSave.bind(this);
    }
    componentWillMount() {}
    componentDidMount() {
        //编辑状态
        if(this.props.params.departmentId == "0"&&this.props.params.isEdit!=0){
            let url=allRouter.patientOrigin+'/department/one/'+this.props.params.isEdit;
            $.ajax({
                url:url,
                type:'GET',
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:data=>{
                    console.log(data);
                    if(data.code===200){
                        this.props.form.setFieldsValue({
                            departmentName:data.department.name,
                            status:data.department.state,
                        });
                    }else{
                        console.log("获取科室名称出错");
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
            this.getEmployeeList();
        }
    }

    //获取员工列表，并把该科室下的员工过滤
    getEmployeeList() {
        //console.log(1);
        let url=allRouter.patientOrigin+'/doctor/list';
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log('员工列表');
                console.log(data);
                let relatedDoctorList=[];
                if(data.code===200){
                    data.users.map(item=>{
                        if(item.department.length){
                            item.department.map(item1=>{
                                if(item1._id==this.props.params.isEdit){
                                    relatedDoctorList.push({name:item.name,index:item._id});
                                }
                            })
                        }
                    });
                    this.setState({
                        relatedDoctorList
                    })
                }else{
                    console.log("获取员工列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }

    //保存科室
    saveData(){
        this.props.form.validateFields((err,values)=> {
            //如果是undefined，则返回
            if(!values.departmentName){
                return;
            }
            console.log(err);
            if(err){
                return;
            }
            if(this.state.handnamed){
                message.error('科室名称已存在，请修改',1);
                return;
            }
            //即是编辑状态
            if(this.props.params.departmentId == "0"&&this.props.params.isEdit!=0){
                // console.log(values.status);
                if(values.status==="禁用"){
                    if(this.state.relatedDoctorList.length>0){
                       let confirmString=<span style={{color:'red'}}>该科室关联了医生，不能禁用！</span>;
                        Modal.info({
                            title: '禁用科室',
                            content: confirmString,
                            onOk: () => {}
                        });
                        return;
                    }
                }
                let url=allRouter.patientOrigin+'/department/update';
                $.ajax({
                    url:url,
                    type: "POST",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        id:this.props.params.isEdit,
                        name:values.departmentName,
                        state:values.status,
                    },
                    success:data=>{
                        if(data.code==200){
                            message.info('更改科室名称成功',);
                            browserHistory.push('/departmentsManage');
                        }else{
                            message.info('更改科室名称错误');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
                return;
            }
            //即是新增二级科室
            if(this.props.params.departmentId != "0"&&this.props.params.isEdit==0){
                let url=allRouter.patientOrigin+'/department/save';
                $.ajax({
                    url:url,
                    type: "POST",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        name:values.departmentName,
                        state:values.status,
                        id:this.props.params.departmentId,
                        grade:2,
                    },
                    success:data=>{
                        console.log(data);
                        if(data.code===200){
                            message.info('科室增加成功',);
                            browserHistory.push('departmentsManage');
                        }else if(data.code==201){
                            // this.props.form.setFields({
                            //     departmentName: {value: values.departmentName, errors: '科室名称已存在，请修改'},
                            // })
                            message.error('科室名称已存在，请修改',1);
                        }else{
                            message.info('科室名称增加失败');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
                return;
            }
            //即是新增一级科室
            if(this.props.params.departmentId == "0"&&this.props.params.isEdit==0){
                let url=allRouter.patientOrigin+'/department/save';
                $.ajax({
                    url:url,
                    type: "POST",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        name:values.departmentName,
                        state:values.status,
                        grade:1,
                    },
                    success:data=>{
                        console.log(data);
                        if(data.code===200){
                            message.info('科室增加成功',);
                            browserHistory.push('departmentsManage');
                        }else if(data.code===201){
                            // this.props.form.setFields({
                            //     departmentName: {value: values.departmentName, errors: '科室名称已存在，请修改'},
                            // })
                            message.error('科室名称已存在，请修改',1);
                        }else{
                            message.info('科室名称增加失败');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
                return;
            }
        })
    }
    //取消保存
    cancelSave(){
        Modal.confirm({
            title:'取消保存',
            content:'确认取消保存并返回科室列表页面吗？',
            onCancel:()=>{},
            onOk:()=>{
                browserHistory.push('departmentsManage');
            }
        })
    }

    //验证名称是否重复
    hadnamed(e){
        console.log(e.target.value);
        let scheduleName = e.target.value
        let url=allRouter.patientOrigin+'/department/hadnamed';
        $.ajax({
            url: url,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data: {
                name:e.target.value
            },
            success:data => {
                console.log(data);
                if(data.code==201){
                    this.props.form.setFields({
                        departmentName: { value: scheduleName,errors: [new Error(data.mes)] }
                    });
                    this.setState({
                        handnamed:true
                    })
                }else{
                    this.setState({
                        handnamed:false
                    })
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    render() {
        const formItemLayout = { labelCol: { span: 2 }, wrapperCol: { span: 18 } };
        const { getFieldDecorator } = this.props.form;
        return (
            <div className='container'>
                <div className='add-department-box'>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="科室名称" style={{ display: 'inline-block', width: '100%' }} >
                            {getFieldDecorator('departmentName', {
                                rules: [
                                    { required: true, message: '科室名称不能为空' },
                                    { max: 15, message: '最多不能超过15个字' },
                                    { pattern: /^([\u4e00-\u9fa5])+$/, message: '请输入中文' }
                                ],
                            })(
                                <Input placeholder="请输入科室名称" onKeyUp={this.hadnamed.bind(this)}/>
                            )}
                        </FormItem>
                    </div>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="状态" style={{ display: 'inline-block', width: '100%' }} >
                            {getFieldDecorator('status', {
                                initialValue: "启用",
                                rules: [{ required: true, message: '状态不能为空' }],

                            })(
                                <Select style={{ width: '100% '}} >
                                    <Option value="启用">启用</Option>
                                    <Option value="禁用">禁用</Option>
                                </Select>
                            )}
                        </FormItem>
                    </div>
                    <div className="related-stores">
                        {this.props.params.isEdit!=0?<ul>
                            <li>已关联医生：</li>
                            {this.state.relatedDoctorList.map(item=>{
                                return <li key={item.index}><Link to="">{item.name}</Link></li>
                            })}
                        </ul>:''}

                    </div>
                    <div style={{maxWidth:800,textAlign:'right',marginTop:10}}>
                        <Button type='primary' style={{marginRight:15}} onClick={this.saveData}>确定</Button>
                        <Button onClick={this.cancelSave}>取消</Button>
                    </div>
                </div>
            </div>
        )
    }
}
const AddFirstDepartmentForm = Form.create()(AddFirstDepartment);
export default AddFirstDepartmentForm;
